class ChatField {
    constructor(playground) {
        this.playground = playground
        this.$history =  $(`<div class="game-chat-field-history"></div>`)
        this.$input = $(`<input type="text" placeholder="esc关闭聊天框" class="game-chat-field-input"></div>`)

        this.$history.hide()
        this.$input.hide()
        this.func_id = null

        this.playground.$playground.append(this.$history)
        this.playground.$playground.append(this.$input)

        this.start()
    }

    start() {
        this.add_listening_events()
    }

    add_listening_events() {
        let out = this
        this.$input.keydown(function(e) {
            if(e.which === 27) { //esc
                out.hide_input()
                out.$input.val('')
                return false
            } else if(e.which === 13) { //enter
                let message = out.$input.val()
                let username = out.playground.root.settings.username
                if(message) {
                    out.$input.val('')
                    out.add_message(username, message)
                    out.playground.mps.send_message(username, message)
                }
                return false
            }
        })
    }

    render_message(message) {
        return $(`<div>${message}</div>`)
    }

    add_message(username, text) {
        this.show_history()
        let message = `[${username}]${text}`
        this.$history.append(this.render_message(message))
        this.$history.scrollTop(this.$history[0].scrollHeight)
    }

    show_history() {
        let out = this
        this.$history.fadeIn()

        if(this.func_id) 
            clearTimeout(this.func_id)

        this.func_id = setTimeout(function() {
            out.$history.fadeOut()
            out.func_id = null
        }, 5000)
    }

    show_input() {
        this.show_history()
        this.$input.show()
        this.$input.focus()
    }

    hide_input() {
        this.$input.hide()
        this.playground.game_map.$canvas.focus()
    }
}
